<template>
	<w-app-container class="app-home">
		<fx-page-header title="工厂"></fx-page-header>
		<fxListFilter @resetSearch='resetSearch'>
			<template slot="row-1" >
				<el-form-item label="启停状态：" label-width="110px">
				<el-select v-model="enableState" prop="enableState" placeholder="请选择" clearable size='mini'>
					<el-option
						v-for="item in stateList"
						:key="item.id"
						:label="item.label"
						:value="item.id"
					>
					</el-option>
				</el-select>
				</el-form-item>
			</template>
			<template slot="tools">
				<el-row>
					<el-button type="primary" size='mini' @click="searchFactory">查询</el-button>
					<el-button type="text" size='mini' @click="resetSearch">重置</el-button>
				</el-row>
			</template>
		</fxListFilter>
		<w-table
      ref="multipleTable"
			:listData="factoryData"
			:tableColumn="factoryColumns"
			:showPagination="true"
			:showColumnFilterBtn="false"
			minWidth="100px"
			:listTotal="totalCount"
			@on-table-row-dbclick="editRow"
			@on-size-change="handleSizeChange"
			@on-current-change="handleCurrentChange">
			<div slot="btn-tools-right" class="tools-right">
				<el-button type="danger" plain size='mini' @click="mutileDel">删除</el-button>
				<el-button type="success" plain size='mini' @click="mutileEnable">启用</el-button>
				<el-button type="info" plain size='mini' @click="mutileDiable">停用</el-button>
				<el-button type="primary"	size='mini' icon="el-icon-plus">导入工厂</el-button>
				<el-button type="primary"	size='mini' icon="el-icon-plus" @click="addFactory">新建工厂</el-button>
			</div>
		</w-table>
		<el-dialog :title="dialogTitle" :visible.sync="factoryInfoDialogVisible" width='480px' :before-close="beforeClose">
			<div class="create-area">
			<el-form :model="factoryForm" label-position='right' style='height: 180px' size='mini' label-width='100px' :rules="factoryRules" ref="factoryForm">
					<el-form-item label="所属集团" prop="groupId" label-width="110px">
						<w-select v-model="factoryForm.groupId" :isBlock="true" autocomplete="off" class="form-item-input">
							<el-option
								v-for="item in groupListAll"
								:key="item.id"
								:label="item.name"
								:value="item.id"
								:sign="item.sign"
								:completeSign="item.completeSign"
							>
							</el-option>
						</w-select>
					</el-form-item>
					<el-form-item label="工厂编号" prop="code" label-width="110px">
						<el-input v-model="factoryForm.code" autocomplete="off" class="form-item-input"></el-input>
					</el-form-item>
					<el-form-item label="工厂名称" prop="name" label-width="110px">
						<el-input v-model="factoryForm.name" autocomplete="off" class="form-item-input"></el-input>
					</el-form-item>
					<el-form-item label="联系人" prop="contactName" label-width="110px">
						<el-input v-model="factoryForm.contactName" autocomplete="off" class="form-item-input"></el-input>
					</el-form-item>
					<el-form-item label="电话" prop="mobile" label-width="110px">
						<el-input v-model="factoryForm.mobile" autocomplete="off" class="form-item-input"></el-input>
					</el-form-item>
					<el-form-item label="启停状态" prop="enable" label-width="110px">
						<el-switch v-model="factoryForm.enable" active-color="#13ce66" inactive-color="#ff4949" active-value="1" inactive-value="0"></el-switch>
					</el-form-item>
					<el-form-item label="备注" prop="remark" label-width="110px">
						<el-input
								v-model="factoryForm.remark"
								type="textarea"
								:rows="3"
								:maxlength="200"
								placeholder="请输入备注"
								class="form-item-input"
								show-word-limit
								resize="none"
						/>
					</el-form-item>
			</el-form>
			</div>
			<div slot="footer" class="dialog-footer">
					<el-button @click="doClose">取 消</el-button>
					<el-button type="primary" @click="doSave('factoryForm')">保 存</el-button>
			</div>
		</el-dialog>
	</w-app-container>
</template>
<script>
import fxListFilter from '@/components/common/Fx-list-filter.vue'
import FxListStateTag from '@/components/common/Fx-list-state-tag.vue'
import APP_STATE_CONFIG from '@/config/app_state_config.js'

export default {
	name: 'factory',
	components: {
		fxListFilter
	},
	data () {
		return {
			stateList: APP_STATE_CONFIG.enableState,
			enableState: '',
			factoryData: [],
			factoryColumns: [
				{ prop: 'code', label: '工厂编码', required: true, width: '80px' },
				{ prop: 'name', label: '工厂名称', required: true, showOverflowTooltip: true },
				{ prop: 'groupName', label: '所属集团', required: true, showOverflowTooltip: true },
				{ prop: 'contactName', label: '联系人', required: true },
				{ prop: 'mobile', label: '电话', required: true },
				{ prop: 'remark', label: '备注', required: true, showOverflowTooltip: true },
				{
					prop: 'enable',
					label: '启停状态',
					required: true,
					fxRender: this.enableRender
				},
				{
					prop: 'modifyUser', label: '修改人', required: true
				},
				{
					prop: 'modifyDate', label: '修改时间', required: true
				},
				{
					prop: 'createUser', label: '创建人', required: true
				},
				{
					prop: 'createDate', label: '创建时间', required: true
				}],
			totalCount: 0,
			factoryInfoDialogVisible: false,
			dialogTitle: '',
			groupListAll: [],
			factoryForm: {
				code: '',
				name: '',
				contactName: '',
				mobile: '',
				enable: '1',
				groupId: '',
				remark: ''
			},
			factoryRules: {
				groupId: [
					{ required: true, message: '请选择集团', trigger: 'blur' }
				],
				code: [
					{ required: true, message: '请输入工厂编号', trigger: 'change' },
					{ min: 1, max: 18, message: '长度最多18个字符', trigger: 'blur' }
				],
				name: [
					{ required: true, message: '请输入工厂名称', trigger: 'change' },
					{ min: 1, max: 50, message: '长度最多50个字符', trigger: 'blur' }
				],
				contactName: [
					{ min: 1, max: 50, message: '长度最多50个字符', trigger: 'blur' }
				],
				mobile: [
					{ min: 1, max: 20, message: '长度最多20个字符', trigger: 'blur' }
				],
				remark: [
					{ min: 1, max: 200, message: '长度最多200个字符', trigger: 'blur' }
				]
			},
			fxDataVerification: null
		}
	},
	created () {
		this.onRefreshFactoryList()
	},
	computed: {
		enableFormaterState (val, key) {
			return (val, key) => {
				return this.$fxStateMiddleware.getStateObj('enableState')(val)[key]
			}
		}
	},
	methods: {
		beforeClose () {
			this.VerityCompanyData()
		},
		doClose () {
			this.VerityCompanyData()
		},
		VerityCompanyData () {
			const isChange = !this.fxDataVerification.checkData(this.factoryForm)
			if (isChange) {
				this.$fxCommon.orderListFrontFunc('VeritybeforeClose').then(() => {
					this.doSave('factoryForm')
				}).catch(() => {
					this.factoryInfoDialogVisible = false
				})
				return false
			} else {
				this.factoryInfoDialogVisible = false
			}
		},
		// 列表数据
		onRefreshFactoryList (page) {
			const searchParams = {
				pageNum: (this.$refs.multipleTable && this.$refs.multipleTable.getPaginationParams().pageNum) || 1,
				pageSize: (this.$refs.multipleTable && this.$refs.multipleTable.getPaginationParams().pageSize) || 20
			}
			if (this.enableState !== '') {
				searchParams.params = {}
				searchParams.params.enable = this.enableState
			}
			return new Promise(resolve => {
				this.$fxApi('factory.findAllFactorys')({
					data: searchParams
				}).then(res => {
					this.totalCount = this.$fxUtils.toNumber(res.total)
					this.factoryData = res.data
					this.$refs.multipleTable.clearSelected()
					resolve()
				})
			})
		},
		handleSizeChange (val) {
			this.onRefreshFactoryList()
		},
		handleCurrentChange (val) {
			this.onRefreshFactoryList()
		},
		addFactory () {
			this.getNextCode().then(this.showDialog)
		},
		showDialog (code) {
			this.factoryInfoDialogVisible = true
			if (this.$refs.factoryForm) {
				this.$refs.factoryForm.resetFields()
			}
			this.factoryForm.code = code
			this.factoryForm.id = ''
			this.findGroupListAll().then(res => {
				this.factoryForm.groupId = res[0].id
				this.fxDataVerification = this.$fxUtils.fxDataVerification(this.factoryForm)
			})
			this.dialogTitle = '新建工厂'
		},
		renderFactoryInfo (res) {
			this.factoryForm = res
			this.factoryForm.enable = res.enable ? '1' : '0'
			this.fxDataVerification = this.$fxUtils.fxDataVerification(this.factoryForm)
		},
		doSave (formName) {
			this.$refs[formName].validate((valid) => {
				if (valid) {
					this.saveOrUpdateFactory().then(this.$fxCommon.orderSuccess('save')).then(() => {
						this.factoryInfoDialogVisible = false
						this.onRefreshFactoryList(1)
					})
				} else {
					return false
				}
			})
		},
		editRow (row, column, event) {
			this.factoryInfoDialogVisible = true
			this.findGroupListAll()
			this.dialogTitle = '修改工厂'
			this.findFactoryDetailById(row).then(this.renderFactoryInfo)
		},
		// 批量删除
		mutileDel () {
			const _selData = this.$refs.multipleTable.selectedRowArr
			return this.$fxCommon.orderListFrontFunc('deleteMulity', _selData)
				.then(this.deleteFactory)
				.then(this.$fxCommon.orderSuccess('deleteMulity'))
				.then(this.searchFactory)
		},
		// 批量启用
		mutileEnable () {
			const _selData = this.$refs.multipleTable.selectedRowArr
			return this.$fxCommon.orderListFrontFunc('enableMulity', _selData).then(() => {
				this.handleState(1).then(this.$fxCommon.orderSuccess('enableMulity')).then(this.searchFactory)
			})
		},
		// 批量停用
		mutileDiable () {
			const _selData = this.$refs.multipleTable.selectedRowArr
			return this.$fxCommon.orderListFrontFunc('disableMulity', _selData).then(() => {
				this.handleState(0).then(this.$fxCommon.orderSuccess('disableMulity')).then(this.searchFactory)
			})
		},
		// 启用 停用
		handleState (type) {
			const _selData = this.$refs.multipleTable.selectedRowArr
			const ids = []
			_selData.forEach((v) => {
				ids.push(v.id)
			})
			return new Promise(resolve => {
				this.$fxApi('factory.updateEnables')({
					data: {
						enable: type,
						factoryIds: ids
					}
				}).then(res => {
					resolve(res)
				})
			})
		},
		resetSearch () {
			this.enableState = ''
		},
		// 查询工厂
		searchFactory () {
			this.onRefreshFactoryList()
		},
		// 获取编号
		getNextCode () {
			return new Promise(resolve => {
				this.$fxApi('factory.getNextCode').then(res => {
					resolve(res)
				})
			})
		},
		// 获取集团
		findGroupListAll () {
			return new Promise(resolve => {
				this.$fxApi('factory.findGroupListAll').then(res => {
					this.groupListAll = res
					resolve(res)
				})
			})
		},
		// 获取工厂信息
		findFactoryDetailById (row) {
			return new Promise(resolve => {
				this.$fxApi('factory.findFactoryDetailById')({
					query: {
						id: row.id
					}
				}).then(res => {
					resolve(res)
				})
			})
		},
		// 新建更新工厂信息
		saveOrUpdateFactory () {
			const { code, id, contactName, enable, groupId, mobile, name, remark, address } = this.factoryForm
			const postData = {
				id,
				code,
				contactName,
				enable,
				groupId,
				mobile,
				name,
				remark,
				address
			}
			return new Promise(resolve => {
				this.$fxApi('factory.saveOrUpdate')({
					data: postData
				}).then(res => {
					resolve(res)
				})
			})
		},
		// 删除工厂信息
		deleteFactory () {
			const _selData = this.$refs.multipleTable.selectedRowArr
			const ids = []
			_selData.forEach((v) => {
				ids.push(v.id)
			})
			return new Promise(resolve => {
				this.$fxApi('factory.deleteFactoryMulity')({
					data: {
						factoryIds: ids
					}
				}).then(res => {
					resolve(res)
				})
			})
		},
		enableRender (h, { row }) {
			return <FxListStateTag
				icon={this.enableFormaterState(row.enable, 'icon')}
				label={this.enableFormaterState(row.enable, 'label')}
			></FxListStateTag>
		}
	}
}
</script>
<style lang="stylus" scoped>
@import '~$assets/stylus/varsty.styl'
.create-area {
	width: 100%
	height: 350px
	box-sizing: border-box
	.form-item-input {
		width:280px
	}
}
</style>
